package com.hxzy.config.security.handler;

import cn.hutool.core.util.StrUtil;
import com.hxzy.config.security.AdminLoginResp;
import com.hxzy.config.security.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义令牌验证器
 */
@Component
public class JwtTokenFilter extends OncePerRequestFilter {


    @Autowired
    private TokenService tokenService;


    /**
     * 过滤器filter
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //取得令牌
        String jwtToken=request.getHeader("Authorization");
        //如果有令牌，验证令牌有效性
        if(StrUtil.isNotBlank(jwtToken)){
            AdminLoginResp adminLoginVO = this.tokenService.validatorToken(jwtToken);
            if(adminLoginVO!=null){
                //放到 spring security的本地线程池中
                UsernamePasswordAuthenticationToken  userToken=new UsernamePasswordAuthenticationToken(adminLoginVO,adminLoginVO.getPassword(),adminLoginVO.getAuthorities());

                userToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
               // 本地线程池中存放数据
                SecurityContextHolder.getContext().setAuthentication(userToken);

                //要不要为令牌加时间
                this.tokenService.refreshToken(adminLoginVO);
            }
        }

        //放行,交给后面的spring security Filter来处理
        filterChain.doFilter(request,response);
    }
}
